package cn.kgc.web.service;

import cn.kgc.common.entity.Article;
import cn.kgc.common.entity.Category;
import cn.kgc.common.entity.DataPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Created by teacher ZHANG on 2023/2/1
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${rest.article.url}")
    private String articleUrl;
    @Value("${rest.category.url}")
    private String categoryUrl;

    @Override
    public DataPage<HashMap<String, Object>> listArticles(Integer categoryId, Integer pageNum, Integer pageSize) {
        String url = String.format("%s?categoryId=%d&pageNum=%d&pageSize=%d", articleUrl, categoryId, pageNum, pageSize);

        return restTemplate.getForObject(url, DataPage.class);
    }

    @Override
    public List<Category> listCategories() {
        Category[] Categories = restTemplate.getForObject(categoryUrl, Category[].class);

        return Arrays.asList(Categories);
    }

    @Override
    public Article findArticle(Integer articleId) {
        Article[] articles = restTemplate.getForObject(articleUrl + "/" + articleId, Article[].class);

        return articles.length > 0? articles[0] : null;
    }

    @Override
    public List<Article> listByIds(List<Integer> articleIds) {
        StringBuilder builder = new StringBuilder();

        for (Integer articleId : articleIds) {
            if (builder.length() > 0) {
                builder.append(",");
            }

            builder.append(articleId);
        }

        Article[] articles = restTemplate.getForObject(articleUrl + "/" + builder.toString(), Article[].class);

        return Arrays.asList(articles);
    }
}
